﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Http;
using WinnerCMS.BLL;
using WinnerCMS.Common;
using WinnerCMS.Model;

#endregion

namespace WinnerCMS.WebUI.Admin.Controllers
{
    public class ExplorerController : ApiController
    {
        #region 获取文件夹

        /// <summary>
        ///     获取文件夹
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public IList<TreeNode> Folders(TreePostBack data)
        {
            DirectoryInfo di;
            var list = new List<TreeNode>();
            if (data == null)
            {
                di = new DirectoryInfo(WinnerCMS.Common.HttpServer.MapPath("~/"));

                var root = new TreeNode
                {
                    Id = di.FullName,
                    Text = "服务器",
                    CustomField1 = di.FullName,
                    State = "open"
                };
                list.Add(root);

                foreach (var dir in di.GetDirectories())
                {
                    root.Children.Add(new TreeNode
                    {
                        Id = dir.FullName,
                        Text = dir.Name,
                        CustomField1 = dir.FullName,
                        State = "closed"
                    });
                }
            }
            else
            {
                di = new DirectoryInfo(data.Id);
                list.AddRange(di.GetDirectories().Select(dir => new TreeNode
                {
                    Id = dir.FullName,
                    Text = dir.Name,
                    CustomField1 = dir.FullName,
                    State = "closed"
                }));
            }


            return list;
        }

        #endregion

        #region 获取文件

        /// <summary>
        ///     获取文件
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public JqueryDatagridDataSource<List<dynamic>> GetFileList(JqueryDatagridPostBack data)
        {
            DirectoryInfo di;
            if (string.IsNullOrEmpty(data.Path))
            {
                di = new DirectoryInfo(WinnerCMS.Common.HttpServer.MapPath("~/"));
            }
            else
            {
                di = new DirectoryInfo(data.Path);
            }
            var jdds = new JqueryDatagridDataSource<List<dynamic>>();

            var pp = new PagingParam {PageNo = data.Page, PageSize = data.Rows};

            var filelist = di.GetFiles();
            if (data.Sort == "LastWriteTime" && data.Order == "desc")
            {
                filelist = filelist.OrderByDescending(x => x.LastWriteTime).ToArray();
            }
            if (data.Sort == "LastWriteTime" && data.Order == "asc")
            {
                filelist = filelist.OrderBy(x => x.LastWriteTime).ToArray();
            }
            if (data.Sort == "Name" && data.Order == "desc")
            {
                filelist = filelist.OrderByDescending(x => x.Name).ToArray();
            }
            if (data.Sort == "Name" && data.Order == "asc")
            {
                filelist = filelist.OrderBy(x => x.Name).ToArray();
            }


            filelist = filelist.Skip(pp.Skip).Take(pp.PageSize).ToArray();
            var list = filelist.Select(fi => new
            {
                Extension = fi.Extension.Remove(0, 1),
                fi.Name,
                fi.FullName,
                DelFullName = fi.FullName,
                FileSize = "",
                fi.LastWriteTime
            }).Cast<dynamic>().ToList();

            jdds.Rows = list;
            jdds.total = di.GetFiles().Count();

            return jdds;
        }

        #endregion

        /// <summary>
        ///     删除文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Result DeleteFile(string path)
        {
            var res = new Result();
            try
            {
                File.Delete(path);
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
                return res;
            }
            return res;
        }

        /// <summary>
        ///     删除文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Result DeleteDirectory(string path)
        {
            var res = new Result();
            try
            {
                Directory.Delete(path, true);
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
                return res;
            }
            return res;
        }

        public Result NewFolder(string path, string name)
        {
            var res = new Result();
            try
            {
                Directory.CreateDirectory(path + "\\" + name);
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
                return res;
            }
            return res;
        }

        public Result RenameFolder(string sourcePath, string newname)
        {
            var res = new Result();
            try
            {
                if (sourcePath.Equals(HttpContext.Current.Server.MapPath("~/")))
                {
                    res.Errors = "根目录没法修改。";
                    return res;
                }
                var source = new DirectoryInfo(sourcePath);

                var destinationPath = source.Parent.FullName + "\\" + newname;
                source.MoveTo(destinationPath);
            }
            catch (Exception ex)
            {
                res.Errors = ex.Message;
                return res;
            }
            return res;
        }
    }
}